package org.jeecg.modules.wms.listener;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.event.RequisitionOutboundEvent;
import org.jeecg.modules.wms.service.IWmsOutboundService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 领料单出库事件监听器
 * 监听OMS模块发布的领料单出库事件，创建对应的出库单
 */
@Slf4j
@Component
public class RequisitionOutboundEventListener {
    
    @Autowired
    private IWmsOutboundService wmsOutboundService;
    
    /**
     * 处理领料单出库事件
     * 异步处理，避免影响OMS模块的主流程
     * 
     * @param event 领料单出库事件
     */
    @Async("eventTaskExecutor")
    @EventListener
    public void handleRequisitionOutboundEvent(RequisitionOutboundEvent event) {
        try {
            log.info("接收到领料单出库事件: 领料单号={}, 订单号={}, 租户ID={}", 
                    event.getRequisitionNo(), event.getOrderNo(), event.getTenantId());
            
            // 调用WMS出库单服务创建出库单
            boolean result = wmsOutboundService.createOutboundFromRequisition(
                event.getRequisitionId(),
                event.getRequisitionNo(),
                event.getOrderId(),
                event.getOrderNo(),
                event.getWarehouseId(),
                event.getProfileList(),
                event.getAccessoryList(),
                event.getTenantId()
            );
            
            if (result) {
                log.info("成功处理领料单出库事件: 领料单号={}, 订单号={}", 
                        event.getRequisitionNo(), event.getOrderNo());
            } else {
                log.warn("处理领料单出库事件失败: 领料单号={}, 订单号={}", 
                        event.getRequisitionNo(), event.getOrderNo());
            }
            
        } catch (Exception e) {
            log.error("处理领料单出库事件异常: 领料单号={}, 订单号={}", 
                    event.getRequisitionNo(), event.getOrderNo(), e);
        }
    }
}
